import React, { Component } from 'react';
import { connect } from 'umi';
import { Tag, message } from 'antd';
import groupBy from 'lodash/groupBy';
import moment from 'moment';
import NoticeIcon from '../NoticeIcon';
import styles from './index.less';
import { useEffect } from 'react';
import { mapNotice } from '@/components/NoticeIcon/message'

const GlobalHeaderRight = (props) => {
  const {
    dispatch,
    myInfo,
    noticeLoading,
    onNoticeVisibleChange,
    unReadNotice,
    unReadNoticeCnt,
    unReadMessage,
    unReadMessageCnt,
    unReadEvent,
    unReadEventCnt,
    isNeedReQuery
  } = props;

  const queryData = () => {
    if (dispatch && myInfo.id) {
      dispatch({
        type: 'message/queryUnReadMessage',
      });
      dispatch({
        type: 'message/queryMockMessage',
      });
    }
  }
  useEffect(() => {
    queryData();
  }, [myInfo,isNeedReQuery]);

  useEffect(() => {
    const timerID = setInterval(
      () => {
        queryData()
      },
      1000 * 60 * 3
    );
    return () => {
      clearInterval(timerID);
    }
  }, []);

  const changeReadState = (messageType, clickedItem) => {
    const { id } = clickedItem;
    console.log(messageType, clickedItem);
    if (clickedItem.isRead === 1) {
      return;
    }
    if (dispatch) {
      switch (messageType) {
        case 'notice':
          dispatch({
            type: 'message/setNoticeReaded',
            payload: id,
          });
          return;
        case 'messagge':
        case 'event':
      }
    }
  };

  const handleNoticeClear = (title, key) => {
    message.success(`${'清空了'} ${title}`);
    if (dispatch) {
      switch (key) {
        case 'notice':
          const ids = unReadNotice.filter(notice => notice.isRead === 0).map(notice => notice.id);
          dispatch({
            type: 'message/clearUnReadNotice',
            payload: ids
          });
          return;
        case 'messagge':
        case 'event':
      }
    }
  };

  return (
    <NoticeIcon
      className={styles.action}
      count={(unReadNoticeCnt || 0) + (unReadEventCnt || 0) + (unReadMessageCnt || 0)}
      onItemClick={(tabKey, item) => {
        changeReadState(tabKey, item);
      }}
      loading={noticeLoading}
      clearText="清空"
      viewMoreText="查看更多"
      onClear={(title, key) => {
        handleNoticeClear(title, key)
      }}
      onPopupVisibleChange={onNoticeVisibleChange}
      onViewMore={() => message.info('Click on view more')}
      clearClose
    >
      <NoticeIcon.Tab
        tabKey="notice"
        count={unReadNoticeCnt || 0}
        list={unReadNotice}
        title="通知"
        emptyText="你已查看所有通知"
        showViewMore
      />
      <NoticeIcon.Tab
        tabKey="message"
        count={unReadMessageCnt || 0}
        list={unReadMessage}
        title="消息"
        emptyText="您已读完所有消息"
        showViewMore
      />
      <NoticeIcon.Tab
        tabKey="event"
        title="待办"
        emptyText="你已完成所有待办"
        count={unReadEventCnt || 0}
        list={unReadEvent}
        showViewMore
      />
    </NoticeIcon>
  );
}

const getNoticeData = (notices) => {
  if (!notices || notices.length === 0 || !Array.isArray(notices)) {
    return {};
  }
  const newNotices = notices.map((notice) => {
    const newNotice = { ...notice };

    if (newNotice.datetime) {
      newNotice.datetime = moment(notice.datetime).fromNow();
    }

    if (newNotice.id) {
      newNotice.key = newNotice.id;
    }

    if (newNotice.extra && newNotice.status) {
      const color = {
        todo: '',
        processing: 'blue',
        urgent: 'red',
        doing: 'gold',
      }[newNotice.status];
      newNotice.extra = (
        <Tag
          color={color}
          style={{
            marginRight: 0,
          }}
        >
          {newNotice.extra}
        </Tag>
      );
    }

    return newNotice;
  });
  return groupBy(newNotices, 'type');
};


const messageMapper = ({ user, message, global, loading }) => {
  const messageData = getNoticeData(message.unReadMessage);
  const unReadNotice = mapNotice(message.unReadNotice)
  return {
    myInfo: user.myInfo,
    collapsed: global.collapsed,
    unReadNotice: unReadNotice,
    unReadNoticeCnt: message.unReadNoticeCnt,
    unReadMessage: messageData['message'],
    unReadEvent: messageData['event'],
    noticeLoading: loading.effects['message.queryUnReadMessage']
  }
};

export default connect(messageMapper)(GlobalHeaderRight);
